package com.elite.groovy.callback

import com.elite.groovy.kh.DHAESUtil
import com.elite.groovy.kh.KHDBConfig
import com.elite.groovy.kh.KHUtil
import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.IpAddressUtil
import com.elite.groovy.util.Util
import com.elite.groovy.kh.getProperty;
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
 * @projectName: Groovy
 * @package: com.elite.groovy.callback
 * @className: saveDispatchInfo
 * @description: 车险调度数据同步接口
 * @author: Rick
 * @date: 2024-11-18 16:13
 * @version: 1.0
 */

class DispatchInfo implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(DispatchInfo.class);

    String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        long startTime = System.currentTimeMillis();

        //初始化
        JSONObject result = new JSONObject();


        // 调用IP过滤
        if (KHDBConfig.getParam(eliteBean, "#APIIP") == "1" && !KHUtil.getRemoteHost(request)) {
            log.warn("API被非法IP调用-Request Not Allow!" + IpAddressUtil.getIpAddress(request));
            result.put("retCode", "-1");
            result.put("retMessage", "非法IP调用！");
            return result.toString();
        }


        // 获取所有Header
        Map<String, String> mapHeader = new HashMap<String, String>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            log.debug("Call Header-" + key + ":" + value);
            mapHeader.put(key, value);
        }




        String getMethod = request.getMethod();
        log.debug("HTTP请求调用类型 getMethod:" + getMethod);
        String PostBodyString = "";
        if(getMethod.equals("POST")) {
            //接收客户端调用参数
            String PostJson = "";
            //AES解密
            try{
            String PostBody= Util.getRequestBody(request,"utf-8");
            String assertKey = getProperty.get("DispatchAESPassword");
            PostBodyString= DHAESUtil.decrypt(PostBody, assertKey)
            }catch (Exception e){
                result.put("retCode", "-1");
                result.put("retMessage", "错误的加密串！");
                return result.toString();;
            }
            log.info("[调用请求信息]:" + PostBodyString);
        }else{
            result.put("retCode", "-1");
            result.put("retMessage", "错误的请求类型！");
            return result.toString();;
        }



        //初始化数据源
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        try {
            //落库方法
            String outData = saveInfoData(jt, PostBodyString);

            log.debug("总耗时:" + (System.currentTimeMillis() - startTime).toString());
            return outData.toString();

        } catch (Exception e) {
            log.error("HTTP请求调用错误，接口处理异常：" + e.getMessage(), e);
            result.put("retCode", "-1");
            result.put("retMessage", "内部错误！");
            return result.toString();
        }
    }



/**
 *  车险调度数据落库
 */
    static String saveInfoData(JdbcTemplate jt, String PostBodyString) throws Exception {
        // 初始化返回
        JSONObject result = new JSONObject();
        JSONObject BodyOBJ = JSONObject.fromObject(PostBodyString)
        try{
        // 调用参数信息
        String ClmNo = BodyOBJ.get("ClmNo"); //报案号
        String AttemperTime = BodyOBJ.get("AttemperTime"); //调度时间
        String SelfClaimFlag = BodyOBJ.get("SelfClaimFlag"); //是否自助理赔案件1-是，0-否
        //检查数据情况
        JSONArray ExamineArr = BodyOBJ.getJSONArray("ExamineList");

        String SelectOBSQL = ''' select REPORT_NO from OBT_SELF_LIST cr where REPORT_NO=? '''
        List SelectOBList = jt.queryForList(SelectOBSQL,ClmNo);

        //检查List是否存在数据，不存在则无效
        if(ExamineArr.size()>0) {
            //检查是否自助理赔案件，如果是，则只写入OBT_SELF_LIST
            if(SelfClaimFlag.equals("1")) {
                //检查OBT_SELF_LIST是否存在数据，如果存在则什么不写入
                if(SelectOBList.size()==0){
                    //标识dh_report为SELF_CLAIM_FLAG=1
                    String UpdateReportSQL = "update dh_report set SELF_CLAIM_FLAG = '1' where CLM_NO = ?";
                    jt.queryForList(UpdateReportSQL, ClmNo);

                    String ReportSQL = "select CLM_NO,POLICY_NO,LICENSE_NO,INSURED_NAME,LINKER_NAME,LINKER_PHONE,REPORT_TIME,HAPPENED_TIME,ACCIDENT_COURSE,BRAND_NAME,EXCLUSIVE_ID from dh_report where clm_no=?";
                    List ReportList = jt.queryForList(ReportSQL, ClmNo);

                    if(ReportList.size()==1){
                        String CLM_NO = ReportList.get(0).get("CLM_NO") == null ? "" : ReportList.get(0).get("CLM_NO").toString();
                        String POLICY_NO = ReportList.get(0).get("POLICY_NO") == null ? "" : ReportList.get(0).get("POLICY_NO").toString();
                        String LICENSE_NO = ReportList.get(0).get("LICENSE_NO") == null ? "" : ReportList.get(0).get("LICENSE_NO").toString();
                        String INSURED_NAME = ReportList.get(0).get("INSURED_NAME") == null ? "" : ReportList.get(0).get("INSURED_NAME").toString();
                        String LINKER_NAME = ReportList.get(0).get("LINKER_NAME") == null ? "" : ReportList.get(0).get("LINKER_NAME").toString();
                        String LINKER_PHONE = ReportList.get(0).get("LINKER_PHONE") == null ? "" : ReportList.get(0).get("LINKER_PHONE").toString();
                        String REPORT_TIME = ReportList.get(0).get("REPORT_TIME") == null ? "" : ReportList.get(0).get("REPORT_TIME").toString();
                        String HAPPENED_TIME = ReportList.get(0).get("HAPPENED_TIME") == null ? "" : ReportList.get(0).get("HAPPENED_TIME").toString();
                        String ACCIDENT_COURSE = ReportList.get(0).get("ACCIDENT_COURSE") == null ? "" : ReportList.get(0).get("ACCIDENT_COURSE").toString();
                        String BRAND_NAME = ReportList.get(0).get("BRAND_NAME") == null ? "" : ReportList.get(0).get("BRAND_NAME").toString();
                        String isSurvey = "1";

                        String Res_key = "ObtSelf_" + KHUtil.getRandomString(27);
                        String InsertOBTSQL = ''' INSERT INTO  OBT_SELF_LIST(SELF_ID,
                                                                            REPORT_NO,
                                                                            POLICY_NUM,
                                                                            LICENSE_NO,
                                                                            INSURED_NAME,
                                                                            VISIT_STAT,
                                                                            LINKER_NAME,
                                                                            LINKER_PHONE,
                                                                            REPORT_TIME,
                                                                            DAMAGE_TIME,
                                                                            ACCIDENT_COURSE,
                                                                            BRAND_NAME,
                                                                            DIAL_COUNT,
                                                                            IS_SURVEY,
                                                                            CREATE_TIME) 
                                                                 VALUES (?,
                                                                 ?,
                                                                 ?,
                                                                 ?,
                                                                 ?,
                                                                 0,
                                                                 ?,
                                                                 ?,
                                                                 ?,
                                                                 ?,
                                                                 ?,
                                                                 ?,
                                                                 0,
                                                                 ?,
                                                                 sysdate) '''

                    int insertOBTNum = jt.update(InsertOBTSQL, Res_key, CLM_NO, POLICY_NO, LICENSE_NO, INSURED_NAME, LINKER_NAME, LINKER_PHONE, REPORT_TIME, HAPPENED_TIME, ACCIDENT_COURSE, BRAND_NAME,isSurvey);
                    log.debug("写入OBT_SELF_LIST结果:" + insertOBTNum + " 【Res_key】:" + Res_key);
                    }else{
                        log.debug("dh_report不存在数据或存在多条数据："+ClmNo);
                    }
                }else{
                    log.debug("OBT_SELF_LIST已存在数据："+ClmNo);
                }
            }else{
                log.debug("不是自助理赔案件！");
            }


            //声明变量
            String ExamineId,DispatchType,ExamineDepartmentCode,ExamineDepartmentName,ExamineAddress,ExaminePrompt,ExamineCode,ExamineName,LossAmount,Phone,State,Devolveflag,AgentId,IsReassignment,CallId,IsSelf,ExamineDeptName,ExamineDeptCode;
            //遍历list写入或更新数据
            for (int i = 0; i < ExamineArr.size(); i++) {
                try{
                // 调用参数信息
                 ExamineId = ExamineArr.get(i)["ExamineId"] == null ? "" :ExamineArr.get(i)["ExamineId"];                         //每个调度任务的唯一标示
                 DispatchType = ExamineArr.get(i)["Type"]== null ? "" :ExamineArr.get(i)["Type"];                            //1、查勘调度2、标的定损调度3、三者定损调度4人伤定损调度 5财产定损调度
                 ExamineDepartmentCode = ExamineArr.get(i)["ExamineDepartmentCode"]== null ? "" :ExamineArr.get(i)["ExamineDepartmentCode"];  //查勘处理机构码
                 ExamineDepartmentName = ExamineArr.get(i)["ExamineDepartmentName"]== null ? "" :ExamineArr.get(i)["ExamineDepartmentName"];   //查勘处理机构
                 ExamineAddress = ExamineArr.get(i)["ExamineAddress"]== null ? "" :ExamineArr.get(i)["ExamineAddress"];                 //查勘、定损地址
                 ExaminePrompt = ExamineArr.get(i)["ExaminePrompt"]== null ? "" :ExamineArr.get(i)["ExaminePrompt"];                       //查勘要点提示
                 ExamineCode = ExamineArr.get(i)["ExamineCode"]== null ? "" :ExamineArr.get(i)["ExamineCode"];                           //查勘人员码
                 ExamineName = ExamineArr.get(i)["ExamineName"]== null ? "" :ExamineArr.get(i)["ExamineName"];                           //查勘人员
                 LossAmount = ExamineArr.get(i)["LossAmount"]== null ? "" :ExamineArr.get(i)["LossAmount"];                             //损失金额
                 Phone = ExamineArr.get(i)["Phone"]== null ? "" :ExamineArr.get(i)["Phone"];                                       //修理厂电话
                 State = ExamineArr.get(i)["State"]== null ? "" :ExamineArr.get(i)["State"];                                       //案件状态 代码
                 Devolveflag = ExamineArr.get(i)["Devolveflag"]== null ? "" :ExamineArr.get(i)["Devolveflag"];                           //通赔标志 0：否 1：是
                 AgentId = ExamineArr.get(i)["AgentId"]== null ? "" :ExamineArr.get(i)["AgentId"];                                   //调度坐席ID，单点登录对应的客服坐席工号
                 IsReassignment = ExamineArr.get(i)["IsReassignment"]== null ? "" :ExamineArr.get(i)["IsReassignment"];                     //是否改派
                 CallId = ExamineArr.get(i)["CallId"]== null ? "" :ExamineArr.get(i)["CallId"];                                     //客服系统电话标示
                 IsSelf = ExamineArr.get(i)["IsSelf"]== null ? "" :ExamineArr.get(i)["IsSelf"];                                     //是否移动查勘1-是；0-否
                 ExamineDeptName = ExamineArr.get(i)["ExamineDeptName"]== null ? "" :ExamineArr.get(i)["ExamineDeptName"];                   //查勘员归属机构
                 ExamineDeptCode = ExamineArr.get(i)["ExamineDeptCode"]== null ? "" :ExamineArr.get(i)["ExamineDeptCode"];                   //查勘员归属机构代码
                    log.debug("获取第一组数据："+ExamineArr.get(i).toString());
                }catch (Exception e){
                    log.debug("ExamineList参数错误！");
                    result.put("retCode", "-1");
                    result.put("retMessage", "ExamineList参数错误！");
                    return result.toString();
                }

                log.debug("AgentId数据"+AgentId);
                //用传参AgentId
                String SelectAgentSQL = ''' select agent_id from staff where loginname=? ''';
                List SelectAgentList = jt.queryForList(SelectAgentSQL, AgentId);
                String UserfocusAgent = "";
                if (SelectAgentList.size() > 0) {
                    UserfocusAgent = SelectAgentList.get(0).get("agent_id");
                }

                //根据报案号检查DH_REPORT_DISPATCH是否存在数据
                String SelectSQL = ''' select examine_id from DH_REPORT_DISPATCH where REPORT_ID=? '''
                List SelectList = jt.queryForList(SelectSQL, ClmNo);

                //存在则更新，否则新增调度数据
                if (SelectList.size() > 0) {
                    log.debug("已有报案调度，不再处理数据！");
//                                            String UpdateSql = ''' UPDATE DH_REPORT_DISPATCH
//                                                                set DISPATCHER=?,
//                                                                DISPATCH_TIME=?,
//                                                                SURVEY_DEPTID=?,
//                                                                IS_SELF=?,
//                                                                SURVEY_DEPTNAME=?,
//                                                                SURVEYOR_ID=?,
//                                                                SURVEYOR_NAME=?,
//                                                                IS_REASSIGNMENT=?
//                                                                where REPORT_ID=?
//                                                                ''';
//                                            jt.update(UpdateSql, UserfocusAgent, AttemperTime, ExamineDepartmentCode, IsSelf, ExamineDepartmentName, ExamineCode, ExamineName, IsReassignment, ClmNo);
                } else {
                    String ReportSQL1 = "select CLM_NO,EXCLUSIVE_ID,FIRSTSITEFLAG,DAMAGECODE,SUBCERTITYPE from dh_report where clm_no=?";
                    List ReportList1 = jt.queryForList(ReportSQL1, ClmNo);
                    if(ReportList1.size()>0){
                    String EXCLUSIVE_ID = ReportList1.get(0).get("EXCLUSIVE_ID") == null ? "" : ReportList1.get(0).get("EXCLUSIVE_ID").toString();
                    String FIRSTSITEFLAG = ReportList1.get(0).get("FIRSTSITEFLAG") == null ? "" : ReportList1.get(0).get("FIRSTSITEFLAG").toString();
                    String DAMAGECODE = ReportList1.get(0).get("EXCLUSIVE_ID") == null ? "" : ReportList1.get(0).get("DAMAGECODE").toString();
                    String SUBCERTITYPE = ReportList1.get(0).get("EXCLUSIVE_ID") == null ? "" : ReportList1.get(0).get("SUBCERTITYPE").toString();
                    //定义主键32位
                    String DISPATCH_ID = "DISPATCH_" + KHUtil.getRandomString(23);
                    String InsertSQL = ''' INSERT INTO DH_REPORT_DISPATCH(DISPATCH_ID,
                                                                        REPORT_ID,
                                                                        DISPATCHER,
                                                                        DISPATCH_TIME,
                                                                        IS_SELF,
                                                                        DISPATCH_TYPE,
                                                                        SURVEY_DEPTID,
                                                                        SURVEY_DEPTNAME,
                                                                        SURVEYOR_ID,
                                                                        SURVEYOR_NAME,
                                                                        SURVERY_POINTS,
                                                                        EXCLUSIVE_ID,
                                                                        IS_REASSIGNMENT,
                                                                        EXAMINE_ID,
                                                                        DISPATCH_STATUS) 
                                                                VALUES(?,
                                                                        ?,
                                                                        ?,
                                                                        ?,
                                                                        ?,
                                                                        ?,
                                                                        ?,
                                                                        ?,
                                                                        ?,
                                                                        ?,
                                                                        ?,
                                                                        ?,
                                                                        ?,
                                                                        ?,
                                                                        '6'
                                                                        )
                                                                ''';
                    int insertDiTNum = jt.update(InsertSQL, DISPATCH_ID, ClmNo, UserfocusAgent, AttemperTime, IsSelf, DispatchType, ExamineDepartmentCode, ExamineDepartmentName, ExamineCode, ExamineName, ExaminePrompt, EXCLUSIVE_ID, IsReassignment, ExamineId);
                    log.debug("写入DH_REPORT_DISPATCH结果:" + insertDiTNum + " 【DISPATCH_ID】:" + DISPATCH_ID);

                    //定义SQL,序列号BUS_ID未增加
                    String InsertOBTBUSSQL = ''' insert into OBT_BUS_LIST (BUS_ID,BATCH,BUS_TYPE,POLICYNUM,STR_K,STR_M,STR_V,STR_W,STR_Z,STR_AA,STR_AF,STR_AG,STR_A)select BUS_ID.nextval,sysdate||?,?, dr.policy_no,dr.license_no,dr.clm_no,dr.insured_name,dr.contect_number,dr.reportor_name,dr.reportor_phone,dr.linker_name,dr.linker_phone,? from dh_report dr where dr.clm_no=? '''
                    String SelectOBTBUSSQL = ''' select count(*) as clmnum from obt_bus_list b where b.str_m=? '''
                    String ifTour = "0";
                    //检查DispatchType是否为查勘调度-------少了时间判断
                    if(DispatchType!=null&&DispatchType.equals("1")){
                        for(int j=0;j<ReportList1.size();j++){
                            //检查obt_bus_list是否存在数据
                            List SelectOBTBUSList = jt.queryForList(SelectOBTBUSSQL, ClmNo);
                            if(SelectOBTBUSList.get(0).get("clmnum")<1){
                                String firstType="DDF";
                                String elseType="DDE";
                                if(FIRSTSITEFLAG.equals("1")){
                                    jt.update(InsertOBTBUSSQL,firstType,firstType,ifTour,ClmNo);

                                }else{
                                    jt.update(InsertOBTBUSSQL,elseType,elseType,ifTour,ClmNo);
                                }

                            }



                        }

                    }

                }else{
                        log.debug("dh_report无数据");
                        result.put("retCode", "1");
                        result.put("retMessage", "无报案数据！");
                        return result.toString();
                    }

                }


            }
        }else{
            result.put("retCode", "1");
            result.put("retMessage", "无ExamineList数据！");
            return result.toString();
        }
        }catch (Exception e){
            log.debug(e.toString());
            result.put("retCode", "-1");
            result.put("retMessage", "内部错误！");
            return result.toString();
        }
        result.put("retCode", "1");
        result.put("retMessage", "success！");
        return result.toString();

    }


}